<template>
	<view class="wdthdrawal">
		<uni-breadcrumb separator="/">
			<uni-breadcrumb-item v-for="(route,index) in routes" :key="index" :to="route.to">
				{{route.name}}
			</uni-breadcrumb-item>
		</uni-breadcrumb>
		<view class="select">
			<text class="titleApp">
				选择订单类型 ：
			</text>
			<uni-data-select
			   v-model="selectTimeVal"
				:clear="false"
			   :localdata="range"
				@change="changeDateSelect2"
			></uni-data-select>
		</view>
		<uni-forms ref="form" :model="formData"  validateTrigger="bind" label-width="0" style="margin:20px" >
			<uni-table ref="table" border  >
				<uni-tr>
					<uni-th align="center" style="width:200px;">
						订单号
					</uni-th>
					<uni-th>
						<uni-forms-item style="margin:0;width: 500px;" >
							<view style="display: flex; align-items: center;">
								<uni-easyinput :disabled="selectTimeVal===2" @change="orderNo" v-model="formData.order_no"></uni-easyinput>
								<button size="mini"  style="margin:0 10px" @click="onIdentifyOrderNo(0,selectTimeVal)" :disabled="selectTimeVal===2" >识别订单号</button>
							</view>
						</uni-forms-item>
					</uni-th>
				</uni-tr>
				<uni-tr>
					<uni-th align="center" style="width:200px;">
						店铺Id
					</uni-th>
					<uni-th>
						<uni-forms-item style="margin:0;width: 500px;" >
							<uni-easyinput v-model="formData.shop_id"></uni-easyinput>
						</uni-forms-item>
					</uni-th>
				</uni-tr>
				<uni-tr>
					<uni-th align="center" style="width:200px;">
						进/出账
					</uni-th>
					<uni-th>
						<uni-data-select
						   v-model="formData.type"
							:clear="false"
						   :localdata="rangeType"
							@change="changeType"
						></uni-data-select>
					</uni-th>
				</uni-tr>
				<uni-tr>
					<uni-th align="center" style="width:200px;">
						账单说明
					</uni-th>
					<uni-th>
						<uni-forms-item  style="margin:0;" >
							<uni-easyinput v-model="formData.text"></uni-easyinput>
						</uni-forms-item>
					</uni-th>
				</uni-tr>
				<uni-tr>
					<uni-th align="center" style="width:200px;">
						账单金额
					</uni-th>
					<uni-th>
						<uni-forms-item  style="margin:0;width: 150px;" >
							<uni-easyinput v-model="formData.price"></uni-easyinput>
						</uni-forms-item>
					</uni-th>
				</uni-tr>
				<uni-tr>
					<uni-th align="center" style="width:200px;">选项</uni-th>
					<uni-th>店铺信息</uni-th>
				</uni-tr>
				<uni-tr>
					<uni-th align="center" style="width:200px;">
						店铺logo
					</uni-th>
					<uni-th>
						<uni-forms-item  style="margin:0" >
							<view class="uploadfile" @click="updateFile('logo')" >
								<image   :src="formData.shop.logo" mode="heightFix" style="width:80px; height:80px "></image>
							</view>
						</uni-forms-item>
					</uni-th>
				</uni-tr>
				<uni-tr>
					<uni-th align="center" style="width:200px;">
						店铺昵称
					</uni-th>
					<uni-th>
						<uni-forms-item style="margin:0;width: 500px;" >
							<uni-easyinput v-model="formData.shop.title"></uni-easyinput>
						</uni-forms-item>
					</uni-th>
				</uni-tr>
				<uni-tr>
					<uni-th align="center" style="width:200px;">选项</uni-th>
					<uni-th>对方信息</uni-th>
				</uni-tr>
				<uni-tr>
					<uni-th align="center" style="width:200px;">
						对方头像
					</uni-th>
					<uni-th>
						<uni-forms-item  style="margin:0" >
							<view class="uploadfile" @click="updateFile('avatar')" >
								<uni-icons v-if="!formData.user.avatar" type="image" color="#afafaf" size="50"></uni-icons>
								<image v-else :src="formData.user.avatar" mode="heightFix" style="width: 80px; height:80px "></image>
							</view>
						</uni-forms-item>
					</uni-th>
				</uni-tr>
				<uni-tr>
					<uni-th align="center" style="width:200px;">
						对方昵称
					</uni-th>
					<uni-th>
						<uni-forms-item style="margin:0;width: 500px;" >
							<uni-easyinput v-model="formData.user.nickname"></uni-easyinput>
						</uni-forms-item>
					</uni-th>
				</uni-tr>
				<uni-tr>
					<uni-th align="center" style="width:200px;">
						对方ID
					</uni-th>
					<uni-th>
						<uni-forms-item style="margin:0;width: 500px;" >
							<uni-easyinput v-model="formData.user._id"></uni-easyinput>
						</uni-forms-item>
					</uni-th>
				</uni-tr>
				<uni-tr>
					<uni-th align="center" style="width:200px;">
						创建时间
					</uni-th>
					<uni-th>
						<uni-forms-item style="margin:0;width:170px;" >
							<uni-easyinput v-model="formData.create_date"></uni-easyinput>
						</uni-forms-item>
						<uni-dateformat :date="formData.create_date"></uni-dateformat>
					</uni-th>
				</uni-tr>
				<uni-tr>
					<uni-td colspan="2">
						<view class="button" style="">
							<button type="primary" class="uni-button" style="width: 150px;" @click="submit">添加</button>
							<navigator open-type="navigateBack" style="margin-left: 15px;">
								<button class="uni-button" style="width: 100px;">返回</button>
							</navigator>
						</view>
					</uni-td>
				</uni-tr>
				
			</uni-table>
		</uni-forms>
	</view>
</template>

<script>
	import {initData,identifyOrderNo,amountreplenishment} from "./add.js"
	const db = uniCloud.database();
	const dbCmd = db.command;
	const dbCollectionName = 'shop_bill';
	export default {
		data() {
			let formData = {
				"shop_id":"",
				"order_no":"",
				"order":{},
				"shop":{},
				"type":1,
				"user":{},
				"price":0,
				"text":"",
				"create_date":Date.now()
			}
			return {
				routes: [
					{to: "/pages/index/index",name: "首页",},
					{to: "/pages/shop/shop/shop-info",name: "商铺信息" },
					{to: "",name: "新增账单" },
				],
				rangeType:[
					{value: 1,text: '入账'},
					{value: 2,text: '出账'},
				],
				loadingAavatar:true,
				selectTimeVal:0,
				range: [
					{value: 0,text: '订单收入'},
					{value: 1,text: '商家自配送'},
					{value: 2,text: '金额补回'},
				],
				formData,
				formOptions: {}
			}
		},
		onReady() {
			this.$refs.form.setRules(this.rules)
		},
		onLoad(e) {
			if (e){
				// console.log(e);
				this.formData.shop_id = e.shop_id
				this.formData.shop._id = e.shop_id
			}
			else {
				
			}
			this.initData()
		},
		watch:{
			"formData.order_no"(val){
				this.formData.order.order_no = val
			}
		},
		methods: {
			initData(){
				let shopId = this.formData.shop_id 
				initData(shopId).then(result => {
					if (result.code === 200)
						return uni.showToast({
							title:"初始化成功",
							mask:true,
							duration:500,
						}).then(()=>{
							this.formData = result.result
						})
					else 
						return uni.showModal({
							title:"初始化失败",
							content:result.error,
							showCancel:false
						}).then(res => {
							if (res.confirm)
								return uni.navigateBack(1)
						})
				})
			},
			onIdentifyOrderNo(recursion=0,type=0){
				uni.showLoading({title:"识别中···",mask:true})
				let orderNo = this.formData.order_no
				identifyOrderNo(orderNo,recursion,type).then(result => {
					uni.hideLoading()
					if (result.code === 200)
						return uni.showToast({
							title:"识别完成",
							mask:true,
							duration:500,
						}).then(()=>{
							// console.log(result);
							this.formData = result.result
						})
					else if (result.code === 202)
						return uni.showModal({
							title:result.error,
							content:"当前订单号在数据库已有记录，点击继续可继续添加",
							confirmText:"#f00",
							confirmText:"继续"
						}).then(res=>{
							// console.log(result);
							if (res.confirm)
								return this.onIdentifyOrderNo(1,type)
						}) 
					else 
						return uni.showModal({
							title:"识别失败",
							content:result.error,
							showCancel:false
						}).then(res=>{
							console.log(result);
						})
				})
			},
			onAmountreplenishment(){
				uni.showLoading({title:"识别中···",mask:true})
				let shopId = this.formData.shop_id
				amountreplenishment(shopId).then(result => {
					uni.hideLoading()
					if (result.code === 200)
						return uni.showToast({
							title:"识别完成",
							mask:true,
							duration:200,
						}).then(()=>{
							// console.log(result);
							this.formData = result.result
						})
					else 
						return uni.showModal({
							title:"识别失败",
							content:result.error,
							showCancel:false
						}).then(res=>{
							console.log(result);
						})
				})
			},
			// 切换账单类型
			changeDateSelect2(e){
				this.formData.text = this.range[e].text
				if (e === 2) {
					this.onAmountreplenishment()
				}
			},
			/**
			 * 验证表单并提交
			 */
			submit() {
				if (!this.formData.shop_id || !this.formData.order_no ||!this.formData.price||!this.formData.type ){
					return uni.showToast({
						title:"数据未填写完整",
						icon:"error",
						mask:true
					})
				}
				let Data = this.deepCopy(this.formData)
				Data.price = parseFloat( (Data.price*100).toFixed(0) )
				this.submitForm(Data)
			},
			// 上传图片
			updateFile(photos) {
				let _this = this
				uni.chooseImage({
					count: 1,
					sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
					sourceType: ['album'], //从相册选择
					success: function(res) {
						uni.showLoading({title: "上传中···"})
						let filePath = res.tempFilePaths[0]
						uniCloud.uploadFile({
							filePath: filePath,
							cloudPath: 'avat' + Date.now() + '.jpg',
							success: function(res) {
								uni.showToast({
									title: "上传完成"
								})
								if (photos == 'avatar') {
									_this.formData.user.avatar = res.fileID
									_this.loadingAavatar = false
								} 
								// else {
								// 	_this.formData.avatar = res.fileID
								// 	_this.loadingAavatar = false
								// }
								
							},
							fail: function() {
								uni.showToast({
									title: "上传失败"
								})
							}
						})
					}
				});
			},
			// 修改审核状态
			change(e) {
				console.log(e);
			},
			// 深拷贝
			deepCopy(obj) {
			    if (obj === null || typeof obj !== 'object') { return obj; }
				 
			    let temp = obj.constructor(); // 给出了正确的原型
			    for (let key in obj) {
			      if (obj.hasOwnProperty(key)) {
			        temp[key] = this.deepCopy(obj[key]); // 使用 this.deepCopy 进行递归调用
			      }
			    }
			    return temp;
			},
			/**
			 * 提交表单
			 */
			submitForm(data) {
				uni.showLoading({title:"添加中···",mask:true})
				let money = data.type===1?data.price:-data.price
				if (!!data.shop_id) {
					uniCloud.importObject("shop").addShopAmount(data.shop_id,money)
				}
				db.collection(dbCollectionName).add(data).then(res => {
					console.log(res);
					uni.hideLoading()
					uni.showModal({
						title:"添加成功",
						content:data.shop.title+'店铺账单添加完成，点击确认返回',
						showCancel:false
					}).then( vm =>{
						if (vm.confirm) return  uni.navigateTo({url:"/pages/shop/shop_bill/list?_uid="+data.shop_id})
					})
				})
			}
		}
	}
</script>
<style>
	.button{
		display: flex;
		justify-content: center;
		margin:20px 0
	}
	.select{
		margin:20px 20px 0 20px;
		display: flex;
		align-items: center;
	}
	.uploadfile {
		width: 80px;
		height: 80px;
		border: 1px solid #ccc;
		display: flex;
		justify-content: center;
		align-items: center;
	}
	.uploadfile:hover {
		background: #f9f9f9;
		cursor: pointer;
	}
	.wdthdrawal{
		padding:20rpx;
		font-size:14px;
	}
</style>